package com.xiaobias.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;

public class Utils {

    private final static Logger logger = LoggerFactory.getLogger(Utils.class);

    /**
     * 执行命令
     *
     * @param cmd         指令
     * @param isOutputLog 是否输出信息
     */
    public static boolean execCmd(String cmd, boolean isOutputLog) {
        BufferedReader br = null;
        try {
            String[] cmdA = {"/bin/sh", "-c", cmd};
            Process process = Runtime.getRuntime().exec(cmdA);
            StreamHandler errorStreamHandler = new StreamHandler(process.getErrorStream(), "ERROR");
            errorStreamHandler.start();
            errorStreamHandler.join();
            StreamHandler outputStreamHandler = new StreamHandler(process.getInputStream(), "STDOUT");
            outputStreamHandler.start();
            outputStreamHandler.join();
        } catch (Exception e) {
            logger.error("cmd error:" + e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 文件拷贝的方法
     */
    public static boolean fileCopy(String src, String des) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(src);
            fos = new FileOutputStream(des);
            int len = 0;
            byte[] buffer = new byte[10 * 1024];
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            logger.error("拷贝文件失败:" + e);
            return false;
        } finally {
            try {
                if (fis != null) fis.close();
                if (fos != null) fos.close();
            } catch (Exception e) {
                logger.info("拷贝文件失败:" + e);
            }
        }
        return true;
    }


    public static String getFileName(String javaName) {
        try {
            int index = javaName.indexOf(".");
            return javaName.substring(0, index);
        } catch (Exception e) {
            return javaName;
        }
    }

    /**
     * 获取SDK的xml中配置信息
     *
     * @param fileName
     */
    public static String getClassPkgName(String fileName) {
        try (FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr)) {
            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("package")) {
                    return line.split("package")[1].replace(";", "").trim();
                }
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

}
